package ch.subgate.pongwars;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Set;

public class LobbyActivity extends Activity implements View.OnClickListener,
        AdapterView.OnItemClickListener {

    private static final int REQUEST_ENABLE_BT = 1;

    private BluetoothAdapter mBtAdapter;

    private ArrayList<BluetoothDevice> mDevices;

    private ArrayAdapter<String> mArrayAdapter;

    private float mSize;

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                mDevices.add(device);
                mArrayAdapter.notifyDataSetChanged();
                Toast.makeText(getApplicationContext(), "Device found", Toast.LENGTH_SHORT).show();
            } // if
        } // onReceive
    }; // BroadcastReceiver

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.lobby_layout);

        mSize = Constants.PADDLE_EASY;

        // Change textview fonts
        Typeface face = Typeface.createFromAsset(getAssets(), "fonts/ca.ttf");
        TextView tv = (TextView)findViewById(R.id.search_button);
        tv.setTypeface(face);
        tv = (TextView)findViewById(R.id.server_button);
        tv.setTypeface(face);
        tv = (TextView)findViewById(R.id.size_button);
        tv.setTypeface(face);

        // Instantiate arrays
        mDevices = new ArrayList<BluetoothDevice>();
        mArrayAdapter = new ArrayAdapter<String>(
                this,
                android.R.layout.simple_list_item_1,
                android.R.id.text1);
        ListView lv = (ListView)findViewById(R.id.search_list);
        lv.setAdapter(mArrayAdapter);

        // Set OnClickListeners
        findViewById(R.id.search_button).setOnClickListener(this);
        findViewById(R.id.server_button).setOnClickListener(this);
        findViewById(R.id.size_button).setOnClickListener(this);
        lv.setOnItemClickListener(this);

        // Get bluetooth adapter and make sure it's enabled
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBtAdapter == null) {
            Toast.makeText(getApplicationContext(), "Bluetooth not supported", Toast.LENGTH_SHORT).show();
        } else {
            if (!mBtAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            } else {
                discoverDevices(true);
            } // if
        } // if

        // Register broadcast receiver
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);
    } // onCreate

    @Override
    public void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
    } // onDestroy

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search_button:
                TextView t = (TextView)v;
                if (t.getText().equals(">Paired")) { t.setText(">All"); discoverDevices(false); }
                else { t.setText(">Paired"); discoverDevices(true); }
                break;
            case R.id.server_button:
                Intent intent = new Intent(LobbyActivity.this, GameActivity.class);
                intent.putExtra("size", mSize);
                intent.putExtra("mode", Constants.MODE_PVPN);
                intent.putExtra("role", true);
                startActivity(intent);
                break;
            case R.id.size_button:
                TextView tv = (TextView)v;
                if (tv.getText().equals(">Easy")) {
                    tv.setText(">Medium");
                    mSize = Constants.PADDLE_MEDIUM;
                } else if (tv.getText().equals(">Medium")) {
                    tv.setText(">Hard");
                    mSize = Constants.PADDLE_HARD;
                } else {
                    tv.setText(">Easy");
                    mSize = Constants.PADDLE_EASY;
                } // if
                break;
        } // switch
    } // onClick

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (mBtAdapter.isDiscovering()) { mBtAdapter.cancelDiscovery(); }
        Intent intent = new Intent(LobbyActivity.this, GameActivity.class);
        intent.putExtra("size", mSize);
        intent.putExtra("mode", Constants.MODE_PVPN);
        intent.putExtra("role", false);
        intent.putExtra("mac", mDevices.get(position).getAddress());
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        startActivity(intent);
    } // onItemClick

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_ENABLE_BT && resultCode == RESULT_OK) {
            discoverDevices(((TextView)findViewById(R.id.search_button)).getText().equals(">Paired"));
        } // if
    } // onActivityResult

    public void discoverDevices(boolean getBonded) {
        mArrayAdapter.clear();
        mDevices.clear();
        if (getBonded) {
            mBtAdapter.cancelDiscovery();
            Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
            if (pairedDevices.size() > 0) {
                for (BluetoothDevice device : pairedDevices) {
                    mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    mDevices.add(device);
                } // for
            } // if
        } else {
            mBtAdapter.startDiscovery();
            Toast.makeText(getApplicationContext(), "Searching...", Toast.LENGTH_SHORT).show();
        } // if
        mArrayAdapter.notifyDataSetChanged();
    } // discoverDevices

} // LobbyActivity
